package handler

import (
	"car-trade-sys/cache"
	"car-trade-sys/model"
	"car-trade-sys/pck"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg": "数据不能为空"})
		return
	}
	redis_key := "login_error_" + username
	errCout, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCout >= 3 {
		c.JSON(200, gin.H{"code": 500, "msg": "密码错误3次，禁止登录"})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "账号或密码错误"})
		return
	}
	if user.Password != pck.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCout == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{"code": 500, "msg": "错误超过3次封禁2两个小时"})
			return
		} else {
			c.JSON(200, gin.H{"code": 500, "msg": "账号或密码错误"})
			return
		}
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功"})
	return
}
func AddUserRole(c *gin.Context) {
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	role_id, _ := strconv.Atoi(c.PostForm("role_id"))
	userRole := model.UserRole{
		UserId: user_id,
		RoleId: role_id,
	}
	tx := model.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	err := model.DB.Create(&userRole).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	err = tx.Commit().Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	var roles []model.Role
	err := model.DB.Table("roles").Joins("left join user_roles on roles.id=user_roles.role_id").
		Where("user_roles.user_id=?", uid).Find(&roles).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": roles})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	var node []model.Node
	err := model.DB.Table("nodes").Joins("left join role_nodes on nodes.id=role_nodes.node_id").
		Where("role_nodes.role_id=?", rid).Find(&node).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": node})
	return
}
func AddCar(c *gin.Context) {
	car_code := c.PostForm("car_code")
	car_name := c.PostForm("car_name")
	car_price, _ := strconv.Atoi(c.PostForm("car_price"))
	car := model.Car{
		CarCode:  car_code,
		CarName:  car_name,
		CarPrice: car_price,
	}
	err := model.DB.Create(&car).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func AddOrder(c *gin.Context) {
	order_code := c.PostForm("order_code")
	order_name := c.PostForm("order_name")
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	car_id, _ := strconv.Atoi(c.PostForm("car_id"))
	order := model.Order{
		OrderCode:  order_code,
		OrderName:  order_name,
		OrderPrice: order_price,
		CarId:      car_id,
	}
	err := model.DB.Create(&order).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "添加失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "添加成功"})
	return
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var carOrder []model.CarOrder
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select("car_code AS CarCode",
				"car_name AS CarName",
				"car_price AS CarPrice",
				"order_code AS OrderCode",
				"order_name AS OrderName",
				"order_price AS OrderPrice").
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").
			Offset(offset).Limit(size).Debug().
			Find(&carOrder)
		jsonData, _ := json.Marshal(carOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrder)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": carOrder, "total": total})
	return
}
func DetailCarOrder(c *gin.Context) {
	id := c.Query("id")
	var carOrder []model.CarOrder
	redis_key := "list_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").
			Select("car_code AS CarCode",
				"car_name AS CarName",
				"car_price AS CarPrice",
				"order_code AS OrderCode",
				"order_name AS OrderName",
				"order_price AS OrderPrice").
			Joins("LEFT JOIN cars ON orders.car_id = cars.id").
			Where("orders.id=?", id).
			Find(&carOrder)
		jsonData, _ := json.Marshal(carOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &carOrder)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": carOrder})
	return
}
